import {defineStore} from 'pinia'
import {UserState} from '../types'
import store from '../pinia'
import perMisson from "./permission";
import Avatar from '@/assets/jflogo.png'
import {post, get} from '@/api/http'

const defaultAvatar = Avatar

const useUserStore = defineStore('user-info', {
    state: () => {
        return {
            userId: 0,
            roleId: 0,
            roles: '',
            token: '',
            userName: '',
            nickName: '',
            avatar: defaultAvatar,
            identification: '',
            systemMode: 0
        }
    },
    actions: {
        getMode(): Promise<void> {
            let _this = this

            return new Promise((resolve) => {
                post({
                    url: 'systemParameter/get'
                }).then(({code, data}) => {
                    if (code === 200) {
                        _this.systemMode = data[0].sysModel
                        resolve()
                    }
                })
            })


        },
        changeMode(mode: number): Promise<void> {
            let _this = this
            return new Promise<void>((resolve, reject) => {
                post({
                    url: 'systemParameter/update/1',
                    data: {
                        sysModel: mode
                    }
                }).then(({code}) => {
                    if (code === 200) {
                        _this.systemMode = mode
                        resolve()
                    } else {

                        reject()
                    }
                })
            })
        },
        getMenu() {

            return get({
                url: 'admin/acl/index/menu'
            })

        },
        saveUser(userInfo: UserState) {
            sessionStorage.setItem('USER-TOKEN-KEY', userInfo.token)

            return new Promise<UserState>(async (resolve) => {

                const bcRoutes: any = (await this.getMenu()).data
                const bcRouteList: any[] = []
                // bcRouteList.push({
                //     parentPath: '',
                //     menuUrl: '/welcome',
                //     menuName: '主控台',
                //     "icon": "icon-zhukongtai",
                //     "routeName": 'welcome',
                //     children: [
                //         {
                //             localFilePath: '/index/welcome.vue',
                //             parentPath: '',
                //             menuUrl: '/welcome',
                //             menuName: '首页',
                //             "icon": "icon-zhukongtai",
                //             "routeName": 'welcome',
                //         }
                //     ]
                // })
                const perList: any[] = []
                if (Array.isArray(bcRoutes.permissionList) && bcRoutes.permissionList.length > 0) {


                    bcRoutes.permissionList[0].children.forEach((o: any, i: number) => {

                        if (o.type == 1) {
                            let temp1 = {
                                "menuUrl": o.path,
                                "menuName": o.name,
                                "icon": o.icon || "icon-settings",
                                "parentPath": "",
                                "routeName": o.path,
                                children: []
                            }
                            //第一层 最左边侧边栏
                            if (Array.isArray(o.children) && o.children.length > 0 && o.select && o.type != 3) {
                                // 第二层
                                o.children.forEach((o1: any, index1: number) => {
                                    // if ('物测室'!= o1.name && 'APS'!= o1.name  && '化验室'!= o1.name   ){
                                    if (o1.type == 1) {
                                        let temp2: any = {
                                            "menuUrl": o1.path,
                                            "menuName": o1.name,
                                            "icon": o1.icon || "icon-settings",
                                            "parentPath": "",
                                            "routeName": o1.path.split('/')[o1.path.split('/').length - 1] + '' + index1,
                                            children: []
                                        };
                                        // 第三层
                                        if (Array.isArray(o1.children) && o1.children.length > 0 && o1.select && o1.type != 3) {
                                            o1.children.forEach((o2: any, i: number) => {
                                                if (o2.type == 1) {
                                                    let temp3 = {
                                                        "menuUrl": o2.path,
                                                        "menuName": o2.name,
                                                        "icon": o2.icon || "icon-settings",
                                                        "parentPath": "",
                                                        "routeName": o2.path.split('/')[o2.path.split('/').length - 1] + index1 + '' + i,
                                                        "localFilePath": o2.component,
                                                    };
                                                    if (o2.path.split('/')[o2.path.split('/').length - 1] == "BIReport"){
                                                        temp3.menuUrl =  temp3.menuUrl +"/:id"
                                                    }
                                                    if (Array.isArray(o2.children)) {
                                                        o2.children.forEach((element: any) => {
                                                            if (element.type === 3) {
                                                                perList.push(element.permissionValue)
                                                            }
                                                        });
                                                    }
                                                    (temp2.children as any[]).push(temp3)
                                                }else if (o2.type == 3) {
                                                    perList.push(o2.permissionValue)
                                                }
                                               
                                            })
                                        } else if (o1.type == 3) {
                                            perList.push(o1.permissionValue)
                                        }
                                        (temp1.children as any).push(temp2)
                                    } else if (o1.type == 3) {
                                        perList.push(o1.permissionValue)
                                    }
                                })

                            }else if (o.type == 3) {
                                perList.push(o.permissionValue)
                            }
                            bcRouteList.push(temp1)
                        } else if (o.type == 3) {
                            perList.push(o.permissionValue)
                        }
                    })
                }
                const p = perMisson()
                p.perList = perList

                sessionStorage.setItem('perList', JSON.stringify(perList))
                sessionStorage.setItem('menuList', JSON.stringify(bcRouteList))

                this.token = userInfo.token

                resolve(userInfo)
            })
        },
        saveUserTow(userInfo: UserState) {

            return new Promise<UserState>(async (resolve) => {

                const bcRoutes: any = (await this.getMenu()).data
                const bcRouteList: any[] = []
                const perList: any[] = []
                if (Array.isArray(bcRoutes.permissionList) && bcRoutes.permissionList.length > 0) {


                    bcRoutes.permissionList[0].children.forEach((o: any, i: number) => {

                        if (o.type == 1) {
                            let temp1 = {
                                "menuUrl": o.path,
                                "menuName": o.name,
                                "icon": o.icon || "icon-settings",
                                "parentPath": "",
                                "routeName": o.path,
                                children: []
                            }
                            //第一层 最左边侧边栏
                            if (Array.isArray(o.children) && o.children.length > 0 && o.select && o.type != 3) {
                                // 第二层
                                o.children.forEach((o1: any, index1: number) => {
                                    // if ('物测室'!= o1.name && 'APS'!= o1.name  && '化验室'!= o1.name   ){
                                    if (o1.type == 1) {
                                        let temp2: any = {
                                            "menuUrl": o1.path,
                                            "menuName": o1.name,
                                            "icon": o1.icon || "icon-settings",
                                            "parentPath": "",
                                            "routeName": o1.path.split('/')[o1.path.split('/').length - 1] + '' + index1,
                                            children: []
                                        };
                                        // 第三层
                                        if (Array.isArray(o1.children) && o1.children.length > 0 && o1.select && o1.type != 3) {
                                            o1.children.forEach((o2: any, i: number) => {
                                                if (o2.type == 1) {
                                                    let temp3 = {
                                                        "menuUrl": o2.path,
                                                        "menuName": o2.name,
                                                        "icon": o2.icon || "icon-settings",
                                                        "parentPath": "",
                                                        "routeName": o2.path.split('/')[o2.path.split('/').length - 1] + index1 + '' + i,
                                                        "localFilePath": o2.component,
                                                    };
                                                    if (o2.path.split('/')[o2.path.split('/').length - 1] == "BIReport"){
                                                        temp3.menuUrl =  temp3.menuUrl +"/:id"
                                                    }
                                                    if (Array.isArray(o2.children)) {
                                                        o2.children.forEach((element: any) => {
                                                            if (element.type === 3) {
                                                                perList.push(element.permissionValue)
                                                            }
                                                        });
                                                    }
                                                    (temp2.children as any[]).push(temp3)
                                                }else if (o2.type == 3) {
                                                    perList.push(o2.permissionValue)
                                                }
                                               
                                            })
                                        } else if (o1.type == 3) {
                                            perList.push(o1.permissionValue)
                                        }
                                        (temp1.children as any).push(temp2)
                                    } else if (o1.type == 3) {
                                        perList.push(o1.permissionValue)
                                    }
                                })

                            }else if (o.type == 3) {
                                perList.push(o.permissionValue)
                            }
                            bcRouteList.push(temp1)
                        } else if (o.type == 3) {
                            perList.push(o.permissionValue)
                        }
                    })
                }
                const p = perMisson()
                p.perList = perList

                sessionStorage.setItem('perList', JSON.stringify(perList))
                sessionStorage.setItem('menuList', JSON.stringify(bcRouteList))
                resolve('成功')
            })
        },
        isTokenExpire() {

            return sessionStorage.getItem('USER-TOKEN-KEY') === null || sessionStorage.getItem('USER-TOKEN-KEY') === ''
        },
        changeNickName(newNickName: string) {
            this.nickName = newNickName
        },
        getMenuList({permissionList}: any) {


        },
        logout() {

            return new Promise<void>((resolve) => {
                sessionStorage.clear()
                this.$reset()
                resolve()
            })
        },
        async getAllMenu() {
            return await get({
                url: 'admin/acl/index/menu'
            })
        }
    },
    presist: {
        enable: true,
        resetToState: true,
        option: {
            exclude: ['userName'],
        },
    },
})

export default useUserStore

export function useUserStoreContext() {
    return useUserStore(store)
}
